package com.studyweb.service;

import com.alibaba.excel.EasyExcel;
import com.studyweb.mapper.VocabularyMapper;
import com.studyweb.pojo.entity.Vocabulary;
import com.studyweb.pojo.excel.VocabularyExcelData;
import com.studyweb.service.listener.VocabularyExcelListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Slf4j
public class VocabularyImportService {

    @Autowired
    private VocabularyMapper vocabularyMapper;

    @Transactional
    public int importVocabularyFromExcel(MultipartFile file, Long userId) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 创建监听器，用于处理每一行数据
        VocabularyExcelListener listener = new VocabularyExcelListener(vocabularyMapper, userId);

        // 使用EasyExcel读取Excel文件
        EasyExcel.read(file.getInputStream(), VocabularyExcelData.class, listener).sheet().doRead();

        // 返回成功导入的词语数量
        return listener.getImportedCount();
    }
}